const express = require('express');
const router = express.Router();
const sectionController = require('../controllers/sectionController');
const { auth, authorize } = require('../middleware/auth');
const { auditLogger, saveBefore } = require('../middleware/audit');
const validate = require('../middleware/validate');
const sectionValidators = require('../validators/section');
const { Section } = require('../models');

// 应用认证中间件到所有路由
router.use(auth);

// 获取所有模板章节
router.get('/sections/templates', 
  sectionController.getAllTemplateSections
);

// 获取项目章节列表
router.get('/projects/:projectId/sections', 
  sectionController.getSections
);

// 创建章节
router.post('/projects/:projectId/sections', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(sectionValidators.createSection),
  auditLogger('create', 'section'),
  sectionController.createSection
);

// 重新排序章节
router.put('/projects/:projectId/sections/reorder', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(sectionValidators.reorderSections),
  auditLogger('update', 'section'),
  sectionController.reorderSections
);

// 获取章节详情
router.get('/sections/:id', 
  sectionController.getSection
);

// 更新章节
router.put('/sections/:id', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(sectionValidators.updateSection),
  saveBefore(Section),
  auditLogger('update', 'section'),
  sectionController.updateSection
);

// 删除章节
router.delete('/sections/:id', 
  authorize('admin', 'project_admin', 'project_user'),
  saveBefore(Section),
  auditLogger('delete', 'section'),
  sectionController.deleteSection
);

module.exports = router;